from functools import wraps
from flask import abort, request, jsonify, session
from flask_login import login_required, current_user
from applications.common.admin_log import admin_log


def admin_required(log: bool = False):
    def decorator(func):
        @login_required
        @wraps(func)
        def wrapper(*args, **kwargs):
            # 检验是否有管理权限
            roles = current_user.role
            for r in roles:
                if r.id == 2:
                    if log:
                        admin_log(request=request, is_access=False)
                    if request.method == 'GET':
                        abort(403)
                    else:
                        return jsonify(success=False, msg="未被授予访问权限!")
            return func(*args, **kwargs)

        return wrapper

    return decorator
